package com.zf.websocket.handle;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定义端点的方式二：实现 WebSocketHandler 来定义端点，在配置中注册 WebSocketHandler 类型的WebSocket端点。
 */
@Component
public class HelloHandler extends AbstractWebSocketHandler {
    public static final ConcurrentHashMap<String, WebSocketSession> USERS = new ConcurrentHashMap<>();

    /**
     * 建立连接后执行
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 获取查询参数
        String query = session.getUri().getQuery();
        System.out.println(query);
        System.out.println(session.getId() + " 建立连接");
        USERS.put(session.getId(), session);
    }

    /**
     * 处理文本消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(session.getId() + " 文本消息：" + message.getPayload());
        session.sendMessage(new TextMessage("发送成功"));
    }

    /**
     * 处理二进制消息，如果不需要处理二进制则数据则不需要实现该方法
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        ByteBuffer byteBuffer = message.getPayload();
        System.out.println("二进制消息：" + byteBuffer.toString());
        // 回写二进制消息
        session.sendMessage(message);
    }

    /**
     * 消息传输过程中出错后执行
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println(session.getId() + " 消息出错: " + exception);
    }

    /**
     * 断开连接后执行
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        USERS.remove(session.getId());
        System.out.println(session.getId() + " 断开连接：" + status);
    }
}
